package com.example.canteen.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    Order findByName(String name);

    @Query(value = "SELECT dish_id FROM order_dish WHERE order_id=:orderId", nativeQuery = true)
    Set<Long> findDishIdByOrderId(long orderId);

    @Query(value = "SELECT quantity FROM order_dish WHERE order_id=:orderId AND dish_id=:dishId", nativeQuery = true)
    Integer findQuantityByOrderIdAndDishId(long orderId, long dishId);

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "UPDATE order_dish SET quantity=:quantity WHERE order_id=:orderId AND dish_id=:dishId", nativeQuery = true)
    void updateQuantityByOrderIdAndDishId(long orderId, long dishId, int quantity);
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "INSERT INTO order_dish (order_id, dish_id, quantity) VALUES (:orderId, :dishId, :quantity)", nativeQuery = true)
    void insertOrderDish(long orderId, long dishId, int quantity);

    @Query(value = "SELECT set_meal_id FROM order_set_meal WHERE order_id=:orderId", nativeQuery = true)
    Set<Long> findSetMealIdByOrderId(long orderId);
    @Query(value = "SELECT quantity FROM order_set_meal WHERE order_id=:orderId AND set_meal_id=:setMealId", nativeQuery = true)
    Integer findQuantityByOrderIdAndSetMealId(long orderId, long setMealId);

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "UPDATE order_set_meal SET quantity=:quantity WHERE order_id=:orderId AND set_meal_id=:setMealId", nativeQuery = true)
    void updateQuantityByOrderIdAndSetMealId(long orderId, long setMealId, int quantity);
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "INSERT INTO order_set_meal (order_id, set_meal_id, quantity) VALUES (:orderId, :setMealId, :quantity)", nativeQuery = true)
    void insertOrderSetMeal(long orderId, long setMealId, int quantity);
    // 添加删除订单菜品关联记录的方法
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "DELETE FROM order_dish WHERE order_id=:orderId AND dish_id=:dishId", nativeQuery = true)
    void deleteOrderDish(long orderId, long dishId);

    // 添加删除订单套餐关联记录的方法
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Modifying
    @Query(value = "DELETE FROM order_set_meal WHERE order_id=:orderId AND set_meal_id=:setMealId", nativeQuery = true)
    void deleteOrderSetMeal(long orderId, long setMealId);
}
